<template>
  <u-modal
    title="图形验证"
    width="95%"
    v-model:show="modalVisible"
    :async-close="true"
    :mask-close-able="false"
    @confirm="submit"
    ref="uModal"
  >
    <!-- 图片验证码 -->
    <div class="modal-content">
      <p class="text-tips" style="margin: 0 0 10px">请输入下方图片中的验证码</p>
      <div class="input-box">
        <input
          class="custom-input"
          type="text"
          v-model="vCode"
          placeholder="请输入"
          :class="{ 'custom-input-error': vCodeError }"
          @blur="vCodeBlur"
        />
        <div class="error-text" v-if="vCodeError">请输入图片验证码</div>
      </div>
      <div class="img-box" v-if="vCodeSrc">
        <img class="img-code" :src="vCodeSrc" />
        <div class="img-code-change" @click="getImgCodeSrc">看不清，换一张</div>
      </div>
    </div>
  </u-modal>
</template>

<script>
import { login, sendSMSCode } from "@/api/qccx";
export default {
  emits: ["success", "changeIndex", "security-verification"],
  data() {
    return {
      vCode: "",
      vCodeError: false,
      modalVisible: false,
      vCodeSrc: "", // 图形验证码
      operateType: "",
    };
  },
  methods: {
    /** 开启弹窗
     * @param {*} codeParam 图形验证码入参 类似 { phone: ****, userName: *****, password: ***** } 中的一个或多个值
     * @param {*} operateType 事件类型：'securityVerify' 安全认证，'resetPassword' 重置密码
     */
    open(codeParam = {}, operateType) {
      this.codeParam = codeParam;
      this.operateType = operateType;
      this.modalVisible = true;

      // 重置
      this.reset();
    },
    /**
     * 图形验证码失焦
     */
    vCodeBlur() {
      this.vCodeError = !this.vCode;
    },
    /**
     * 重置
     */
    reset() {
      // 去除无值提示
      this.vCodeError = false;
      // 更新图片
      this.getImgCodeSrc();
    },
    /***
     * 将对象转化为固定字符串
     *
     */
    stringify(objs, sep = "&", ep = "=") {
      let str = "";
      Object.keys(objs).forEach((obj) => {
        str += obj + ep + objs[obj] + sep;
      });
      return str.slice(0, -1);
    },
    /**
     * 获取图形验证码
     */
    getImgCodeSrc() {
      const param = {
        timeStamp: Date.now(),
      };
      if (this.codeParam.userName) param.userName = this.codeParam.userName;
      if (this.codeParam.phone) param.phone = this.codeParam.phone;
      const env = process.env.NODE_ENV
      if (env == 'development') {
        this.vCodeSrc = `/saas/getValidateCode?` + this.stringify(param);
      } else {
        this.vCodeSrc = `/api/saas/getValidateCode?` + this.stringify(param);
      }
      // 去除 vCode
      this.vCode = "";
    },
    /**
     * 确定
     */
    submit() {
      if (!this.vCode) {
        // Message.warning('请输入图形验证码')
        return;
      }
      // 调用接口
      // 情况1：登录调用验证码，调用登录接口，传入 账号、密码、图形验证码
      if (this.operateType == "login") {
        login({
          userName: this.codeParam.userName,
          password: this.codeParam.password,
          vCode: this.vCode,
        })
          .then((res) => {
            const loginRes = res.result;
            if (loginRes.status) {
              this.modalVisible = false;
              // 登录成功
              this.$emit("success", this.operateType);
            } else {
              // 此时有可能是需要打开安全验证
              const statusCode = loginRes.statusCode;
              if (statusCode) {
                // 需要安全验证
                if (statusCode == 30) {
                  // 手机号后四位
                  const encryptionPhoneNumber = loginRes.message;
                  this.$emit("security-verification", encryptionPhoneNumber);

                  this.$refs.uModal.clearLoading();
                }
              } else {
                uni.showToast({
                  icon: "none",
                  title: "登录失败，" + loginRes.message,
                });

                this.$refs.uModal.clearLoading();
              }
            }
            // 关闭弹窗
            this.modalVisible = false;
          })
          .catch(() => {
            this.reset();
            this.$refs.uModal.clearLoading();
          });
      }
      // 情况2：安全认证-发送短信，传入 账号、图形验证码
      if (this.operateType == "securityVerify") {
        const param = {
          vCode: this.vCode,
        };
        if (this.operateType == "securityVerify") {
          param.userName = this.codeParam.userName;
        }
        if (this.operateType == "resetPassword") {
          param.phone = this.codeParam.phone;
        }
        sendSMSCode(param)
          .then((res) => {
            uni.showToast({
              icon: "none",
              title: res.result.message,
            });
            if (res.result.status) {
              this.$emit("success");
            }
            // 关闭弹窗
            this.modalVisible = false;
          })
          .catch(() => {
            this.reset();
            this.$refs.uModal.clearLoading();
          })
      }
    },
  },
};
</script>
<style lang="less" scoped>
.modal-content {
  padding: 24rpx 24rpx 36rpx 24rpx;
}
.input-box {
  .custom-input {
    width: 100%;
    height: 80rpx;
    font-size: 28rpx;
    border-radius: 6rpx;
    padding: 16rpx 0 16rpx 36rpx;
    border: 2rpx solid #c5c6cd;
    outline-style: none;
  }
  .custom-input:focus {
    outline: none;
    border: 2rpx solid #165dff;
  }
  .custom-input-error {
    outline: none;
    border: 2rpx solid #ff5b5a;
  }
  .error-text {
    height: 44rpx;
    font-size: 28rpx;
    font-family: PingFang SC-Regular, PingFang SC;
    font-weight: 400;
    color: #ff5b5a;
    line-height: 44rpx;
    margin-top: 24rpx;
  }
}
.img-box {
  display: flex;
  align-items: center;
  margin-top: 24rpx;
  .img-code {
    width: 288rpx;
    height: 80rpx;
    margin-left: 0;
    border: 2rpx solid #c5c6cd;
  }
  .img-code-change {
    height: 44rpx;
    line-height: 44rpx;
    font-size: 28rpx;
    color: #86909c;
    height: 44rpx;
    line-height: 44rpx;
    margin-left: 48rpx;
    cursor: pointer;
  }
}
</style>
